<template>
  <div class="index-container">
    <div class="main-header clearfix">
      <el-row>
       <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
          <el-button type="primary"  icon="el-icon-plus" class="sureBtn"  size="medium"  @click="handleAdd" > 新 增 老 人</el-button>
        </el-col>
        <el-col :xs="16" :sm="16" :md="16" :lg="16" :xl="16">
           <div class="search fr">
            <div>
              <el-input  v-model="searchForm.name"   size="medium"  placeholder="老人姓名"></el-input>
            </div>
            <el-button size="medium"   type="primary"   icon="el-icon-search"  class="fr"    @click="onSearch" > 搜索</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="main-content" style="height: calc(100vh - 250px);">
      <main-table
        :columns="tableColumns"
        :data="tableList"
        :loading="loading"
        :pagination="pagination"
         @getData="fetchTableList"
        wrapperHeight="calc(100% - 73px)" height="100%"
      >
      <el-table-column slot="image" fixed="left" label="活动图片" width="150" align="center">
        <template slot-scope="scope">
          <img v-if="scope.row.image" class="contract-icon-img" :src="scope.row.image" @click="handleBigImage(scope.row)" alt="">
        </template>
      </el-table-column>
       <el-table-column slot="action" fixed="right" label="操作" width="300">
         <template slot-scope="scope">
           <!-- <el-button size="mini" type="success" @click="edit(scope.row)">编辑</el-button> -->
           <el-button size="mini" type="primary" @click="handleToImage(scope.row)">导入</el-button>
           <el-button size="mini" type="danger" @click="deleteImg(scope.row)">删除</el-button>
         </template>
       </el-table-column>

      </main-table>
    </div>

    <el-dialog
      title="新增老人"
      v-if="dialogVisible"
      :visible.sync="dialogVisible"
      width="800px"
      :close-on-click-modal="false">
      <older-add @cancle="dialogVisible = false" :data="ruleForm" @load="load"></older-add>
    </el-dialog>


    <el-dialog
      title="编辑老人"
      v-if="dialogEditVisible"
      :visible.sync="dialogEditVisible"
      width="800px"
      :close-on-click-modal="false">
      <older-edit @cancle="dialogEditVisible = false" :data="ruleForm" @load="load"></older-edit>
    </el-dialog>

    <el-dialog title="老人头像" width="600px" :close-on-click-modal="false" :visible.sync="dialogImageVisible" :append-to-body="true">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>

  </div>
</template>
<script>
  import mainTable from "@/components/main-table/index";
  import * as APIDailycare from '@/api/dailycare'
  import { sex, age, elderlyCategory, sourceType, unixToDate } from "@/utils";
  import olderAdd from './components/older-add'
  import olderEdit from './components/older-edit'
  import { mapState } from 'vuex'
  export default {
    name: "helpManager-dailycare-older-list",
    components: {
      mainTable,
      olderAdd,
      olderEdit
    },
    computed: {
      ...mapState('facewebsocket', [
        'deviceMsg',
        'sendFaceMsg'
      ])
    },
    data() {
      return {
        loading: false,
        title: '添加图标',
        dialogVisible: false,
        dialogEditVisible: false,
        dialogImageVisible: false,
        dialogImageUrl:'',
        ruleForm: {},
        searchForm: {
          page: 1
        },
        tableList:[],
        pagination: {
          current: 1,
          size: 10,
          total: 0
        },
        tableColumns: [
         {
           index: true,
           fixed: true
         },
         {
           slot: 'image'
         },
         {
           prop: 'id',
           label: '老人ID'
         },
         {
           prop: 'name',
           label: '老人姓名'
         },
         {
           prop: 'idcard',
           label: '身份证号'
         },
         {
           prop: 'jifen',
           label: '积分'
         },
         {
           prop: 'msg',
           label: '备注'
         },
         {
           prop: 'status',
           label: '状态',
           formatter (row, column, cellValue) {
             if (cellValue == '0') {
               return '未导入'
             } else if (cellValue == '1') {
               return '已导入'
             }
           }
         },
         {
           slot: 'action'
         }
        ],
        key: Math.random(),
        // oldid 删除时老人id
        oldid: '',
      };
    },
    created() {},
    beforeDestroy() {},
    mounted() {
      this.fetchTableList();
      setTimeout(() => {
        this.sendFaceGetAll()
      }, 1000)
    },
    watch: {
      sendFaceMsg: {
        handler: function (newVal) {
          this.init(newVal, this)
        }
      }
    },
    methods: {
      // 人脸设备发送消息
      init (data, _that) {
        /* const { info } = _that
        let device_sn = ''
        if (info.face && info.face.length !== 0) {
          info.face.forEach(item => {
            if (item.type === '1') {
              device_sn = item.device_sn || ''
            }
          })
        } */
        let device_sn = ''
        let userinfo = localStorage.getItem("userdata") || {}
        if(userinfo) {
        	userinfo = JSON.parse(userinfo);
          if(userinfo.hasOwnProperty('facedev') && userinfo.facedev.length != 0){
              userinfo.facedev.forEach(item => {
                 device_sn = item.device_sn || ''
              })
          }
        }
        if (data.cmd == 'upload person' && data.reply == 'ACK') {
          let msg = ''
          switch (data.code) {
            case 0:
              msg = '人员添加成功'
              break
            case 3:
              msg = data.desc || '数据格式错误，请联系管理员'
              break
            case 6:
              msg = '设备内存不足，请清理设备内多余信息'
              break
            case 16:
              msg = '人员可能已存在，请查看人脸库'
              break
            case 20:
              msg = '设备人员录入已满'
              break
            case 21:
              msg = '人员记录已存在'
              break
            case 22:
              msg = '人脸记录不存在，可以添加'
              break
            case 25:
              msg = '提取成员失败，请检查上次图片'
              break
            case 35:
              msg = '图片解码失败，请选择jpg或png图片上传'
              break
            case 36:
              msg = '图片太大，请上传4M大小以内图片'
              break
            case 38:
              msg = '图片人脸尺寸太小，请选择合适图片上传'
              break
            case 39:
              msg = '图片人脸质量太差，请选择清晰图片上传'
              break
            case 40:
              msg = '图片中存在多张人脸，请选择单张人脸图片上传'
              break
            case 41:
              msg = '图片中人脸不完整，请选择完整人脸图片上传'
              break
          }
          if (data.code == 0) {
            _that.load()
            _that.$message.success(msg)
            _that.sendFaceGetAll()
          } else {
            _that.$message.error(msg)
          }
          if (device_sn) {
            const senddata = {
              cmd: 'send_dev',
              device_sn: device_sn,
              data: {
                cmd: 'tts play',
                text: msg
              }
            }
            _that.$face.$ws.send(JSON.stringify(senddata))
          }
        } else if (data.cmd == 'delete person(s)' && data.reply == 'ACK') {
          _that.del()
          if (device_sn) {
            const senddata = {
              cmd: 'send_dev',
              device_sn: device_sn,
              data: {
                cmd: 'tts play',
                text: '人员删除成功'
              }
            }
            _that.$face.$ws.send(JSON.stringify(senddata))
          }
        } else if (data.cmd == 'get allpersonid' && data.reply == 'ACK') {
          let dataids = data.ids
          dataids = dataids.split(',')
          _that.tableList.length && _that.tableList.forEach((item, index) => {
            _that.$set(_that.tableList[index], 'status', '0')
            dataids.forEach((ite, idx) => {
              if (item.id === ite) {
                _that.$set(_that.tableList[index], 'status', '1')
              }
            })
          })
        } else if (data.route == 'error') {
          const msg = data.data && data.data.msg
          _that.$message.error(msg)
          if (device_sn) {
            const senddata = {
              cmd: 'send_dev',
              device_sn: device_sn,
              data: {
                cmd: 'tts play',
                text: msg
              }
            }
            _that.$face.$ws.send(JSON.stringify(senddata))
          }
        }
      },
      // 点击”查询“按钮 => 此时缓存查询参数
      onSearch () {
        this.pagination = {
          current: 1,
          size: 10,
          total: 0
        }
        this.fetchTableList()
      },
      load () {
        this.fetchTableList()
      },
      // 手动清空/搜索
      clear () {
        this.fetchTableList({ page: 1 })
      },
      fetchTableList(pageObj) {
        this.loading = true
        this.searchForm = {
          ...this.searchForm,
          ...pageObj
        }
        APIDailycare.riolderList(this.searchForm).then((resp) => {
          if (resp.code == 200) {
            const { list = [], total = 0 } = resp.data;
            this.tableList = list || []
            this.pagination.total = total;
          }
        }).finally(() => {
         this.loading = false
        });
      },
      edit (row) {
        // this.title = '编辑人脸设备';
        this.key = Math.random();
        this.ruleForm = { ...row }
        this.dialogEditVisible = true;
      },
      handleAdd() {
        // this.title = '添加人脸设备';
        this.dialogVisible = true;
        this.key = Math.random();
        this.ruleForm = { type: '1' };
      },
      handleBigImage (item) {
        this.dialogImageVisible = true
        this.dialogImageUrl = item.image
      },
      cancelOrder(row) {
        this.$confirm("确定删除该条数据, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            APISystem.facedevDelete({ id: row.id }).then((resp) => {
              if (resp.code === 200) {
                this.$message({ type: "success", message: "删除成功!"});
                this.fetchTableList();
              }
            });
          })
          .catch(() => {
          });
      },
      del () {
        if (!this.oldid) {
          this.$message.error('老人ID为空')
          return
        }
        APIDailycare.riolderDelete({ id: this.oldid }).then((res) => {
          this.fetchTableList()
        })
      },
      /** 获取老人头像base64编码 */
      getImageUrlBase64 (imgUrl) {
        return new Promise(function (resolve) {
          window.URL = window.URL || window.webkitURL
          const xhr = new XMLHttpRequest()
          xhr.open('get', imgUrl, true)
          xhr.responseType = 'blob'
          xhr.onload = function () {
            if (this.status === 200) {
              // 得到一个blob对象
              const blob = this.response
              // 至关重要
              const oFileReader = new FileReader()
              oFileReader.onloadend = function (e) {
                // 此处拿到的已经是base64的图片了,可以赋值做相应的处理
                const result = e.target.result
                const image = new Image()
                // 解决跨域问题
                image.setAttribute('crossOrigin', 'anonymous')
                image.src = result
                // image.onload为异步加载
                image.onload = () => {
                  const canvas = document.createElement('canvas')
                  canvas.width = image.width
                  canvas.height = image.height
                  const context = canvas.getContext('2d')
                  context.drawImage(image, 0, 0, image.width, image.height)
                  // 这里的dataurl就是base64类型
                  const dataURL = canvas.toDataURL('image/jpeg', 1)
                  resolve(dataURL)
                }
              }
              oFileReader.readAsDataURL(blob)
            }
          }
          xhr.send()
        })
      },
      urlConversion (path) {
        const reg = /^(https?:\/\/)([0-9a-z.]+)(:[0-9]+)?([/0-9a-z.]+)?(\?[0-9a-z&=]+)?(#[0-9-a-z]+)?/i
        path = path.replace(reg, 'https://$2$3$4$5$6')
        return path
      },
      /** 导入老人base64头像 */
      handleToImage(row) {
        this.$confirm("确定导入该老人, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
              this.importingOlder(row)
          })
          .catch(() => {
          });
      },
      importingOlder (item) {
        /* const { info } = this
        let device_sn = ''
        if (info.face && info.face.length !== 0) {
          info.face.forEach(item => {
            if (item.type === '1') {
              device_sn = item.device_sn || ''
            }
          })
        } */
        let device_sn = ''
        let userinfo = localStorage.getItem("userdata") || {}
        if(userinfo) {
        	userinfo = JSON.parse(userinfo);
          if(userinfo.hasOwnProperty('facedev') && userinfo.facedev.length != 0){
              userinfo.facedev.forEach(item => {
                 device_sn = item.device_sn || ''
              })
          }
        }
        if (item.image) {
          const _this = this
          if (device_sn) {
            const path = this.urlConversion(item.image)
            this.getImageUrlBase64(path).then(res => {
              _this.isToData = 0
              const reg_image = res.split(',')[1]
              const senddata = {
                cmd: 'send_dev',
                device_sn: device_sn,
                data: {
                  cmd: 'upload person',
                  id: item.id,
                  name: item.name,
                  reg_image: reg_image,
                  long_card_id: Number(item.id),
                  customer_text: item.address,
                  upload_mode: 0
                }
              }
              _this.$face.$ws.send(JSON.stringify(senddata))
            })
          } else {
            this.$message.warning('请先去站点管理添加人脸设备号')
          }
        } else {
          this.$message.warning('请先添加人脸头像才能导入')
        }
      },
      sendFaceGetAll () {
       /* const { info } = this
        let device_sn = ''
        if (info.face && info.face.length !== 0) {
          info.face.forEach(item => {
            if (item.type === '1') {
              device_sn = item.device_sn || ''
            }
          })
        } */
        let device_sn = ''
        let userinfo = localStorage.getItem("userdata") || {}
        if(userinfo) {
        	userinfo = JSON.parse(userinfo);
          if(userinfo.hasOwnProperty('facedev') && userinfo.facedev.length != 0){
              userinfo.facedev.forEach(item => {
                 device_sn = item.device_sn || ''
              })
          }
        }
        if (device_sn) {
          const senddata = {
            cmd: 'send_dev',
            device_sn: device_sn,
            data: {
              cmd: 'get allpersonid'
            }
          }
          this.$face.$ws.send(JSON.stringify(senddata))
        } else {
          this.$message.warning('请先去站点管理添加人脸设备号')
        }
      },
      /** 删除老人信息 */
      deleteImg(row) {
        this.$confirm("确定删除该条数据, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
              this.cancelOlder(row)
          })
          .catch(() => {
          });
      },
      cancelOlder (row) {
        if (!row.id) {
          this.$message.error('老人ID为空')
          return
        }
        this.oldid = row.id
        /* const { info } = this
        let device_sn = ''
        if (info.face && info.face.length !== 0) {
          info.face.forEach(item => {
            if (item.type === '1') {
              device_sn = item.device_sn || ''
            }
          })
        } */
        let device_sn = ''
        let userinfo = localStorage.getItem("userdata") || {}
        if(userinfo) {
        	userinfo = JSON.parse(userinfo);
          if(userinfo.hasOwnProperty('facedev') && userinfo.facedev.length != 0){
              userinfo.facedev.forEach(item => {
                 device_sn = item.device_sn || ''
              })
          }
        }
        if (device_sn) {
           const senddata = {
             cmd: 'send_dev',
             device_sn: device_sn,
             data: {
               cmd: 'delete person(s)',
               id: row.id,
               flag: -1
             }
           }
           this.$face.$ws.send(JSON.stringify(senddata))
        } else {
          this.$message.warning('请先去站点管理添加人脸设备号')
        }
      },
    },
  };
</script>
<style lang="scss" scoped>
  .index-container {
    box-sizing: border-box;
    width: 100%;
    padding: 0 30px !important;
    margin: 0 !important;
    background: #fff !important;

    .main-header {
      padding-top: 4px;
      margin-bottom: 24px;

      .search {
        display: inline-block;

        .search-title {
          flex: 0 0 48px;
          width: 48px;
          font-size: 16px;
          line-height: 36px;
          color: #333;
        }
      }

      .search > div {
        display: inline-block;
        margin-left: 20px;
      }
    }
    .task-icon-img{
      width: 80px;
      height: 80px;
    }
  }

  .form-footer {
    padding-left: 100px;
  }

  .dialog-main {
    .table-do {
      margin-bottom: 15px;
    }

    ::v-deep {
      th {
        .cell {
          color: #fff;
        }
      }
    }
  }
  .contract-icon-img{
    width: 40px;
    height: 40px;
    cursor: pointer;
  }
</style>
